package com.woniuxy.carlife.carlifeuserweb.util;


import com.woniuxy.carlife.carlifeuserweb.config.MinioConfig;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.RemoveBucketArgs;
import io.minio.RemoveObjectArgs;
import io.minio.errors.*;

import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * @author qk
 * @ClassName:MinioTemplate
 * @Description:
 * @date 2021/4/8 14:55
 **/

public class MinioTemplate {
    private MinioConfig minioConfig;

    private MinioClient client;
/*
 * 功能描述〈通过构造器将config文件与MinioClient整合〉
 * @author:qk
 * @param:minioConfig，自定义的配置文件
 * @return:
 * @Date 2021/4/8 15:08
 * @throws //
 */

    public  MinioTemplate(MinioConfig minioConfig){
        this.minioConfig=minioConfig;
        this.client=MinioClient.builder()
                .endpoint(minioConfig.getEndpoint())
                .credentials(minioConfig.getAccessKey(),minioConfig.getSecretKey()).build();
    }
    /*
     * 功能描述〈文件上传方法〉
     * @author:qk
     * @param:
     * @return:
     * @Date 2021/4/8 15:10
     * @throws //
     */
    public String uploadFile(String filename, String bucketName, InputStream inputStream,Long size,String contentType){

        PutObjectArgs poa = PutObjectArgs.builder()
                .object(filename).bucket(bucketName).stream(inputStream,size,minioConfig.getPartSize())
                .build();
        System.out.println(minioConfig.getPartSize());
        try {
            client.putObject(poa);
            return minioConfig.getEndpoint()+"/"+bucketName+filename;
        } catch (ErrorResponseException|InsufficientDataException | InternalException |InvalidKeyException
                |InvalidResponseException|IOException
                |NoSuchAlgorithmException|ServerException
                |XmlParserException  e)
        {
            e.printStackTrace();
            throw new RuntimeException("上传失败");
        }
    }
    /*
     * 功能描述〈文件删除方法〉
     * @author:qk
     * @param:
     * @return:
     * @Date 2021/4/8 15:22
     * @throws //
     */
    public boolean deleteFile(String fileName,String bucketName){
        RemoveObjectArgs removeObjectArgs = RemoveObjectArgs.builder().bucket(bucketName).object(fileName).build();
        try {
            client.removeObject(removeObjectArgs);
            return true;
        } catch (ErrorResponseException|InsufficientDataException | InternalException |InvalidKeyException
                |InvalidResponseException|IOException
                |NoSuchAlgorithmException|ServerException
                |XmlParserException  e) {
            e.printStackTrace();
            throw new RuntimeException("删除失败");
        }

    }
}
